package gameUi
{
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;

	/**
	 * 声音管理器
	 * 需要提供播放声音,暂时声音的功能
	 */ 
	public class SoundManager
	{
		public function SoundManager()
		{
		}
		
		private static var _instance:SoundManager;
		
		public static function get instance():SoundManager {
			if(_instance == null){
				_instance = new SoundManager();
			}
			return _instance;
		}
		
		public function play(soundName:String):void {
			if(isPause){
				return;
			}
			var path:String = "../swc/Sound/" + soundName + ".mp3";
			var request:URLRequest = new URLRequest(path);
			var sound:Sound = new Sound();
			sound.addEventListener(IOErrorEvent.IO_ERROR,onError);
			sound.load(request);
			var channel:SoundChannel = sound.play();
			if(channel){
				channel.soundTransform = new SoundTransform(1);
			}
		}
		
		private var backgroundChannel:SoundChannel;
		
		private var backgrounsPosition:Number = 0;
		
		public var isPause:Boolean;
		public function playBackground():void {
			var path:String = "../swc/Sound/back-sound1.mp3";
			var request:URLRequest = new URLRequest(path);
			var sound:Sound = new Sound();
			sound.addEventListener(IOErrorEvent.IO_ERROR,onError);
			sound.load(request);
			backgroundChannel = sound.play(backgrounsPosition,int.MAX_VALUE);
			if(backgroundChannel){
				backgroundChannel.soundTransform = new SoundTransform(1);
			}
		}
		
		private function onError(event:IOErrorEvent):void {
			trace(event.text);
		}
		
		public function playPoints(points:int):void {
			var soundName:String = "sound";
			if(points <= 21){
				soundName += points;
			}else {
				soundName += points + "_bust"; 
			}
			this.play(soundName);
		}
		
		public function pause():void  {
			this.isPause = !this.isPause;
			if(this.isPause){
				backgrounsPosition = backgroundChannel.position;
				backgroundChannel.stop();
			}else {
				this.playBackground();
			}
			
		}
	}
}